package com.es.disped.web.controller.wechat;

import java.io.IOException;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.TimeUnit;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.es.disped.api.user.UserService;
import com.es.disped.api.wechat.WeChatService;
import com.es.disped.common.constant.WeChat;
import com.es.disped.common.model.MsgModel;
import com.es.disped.common.wechat.http.request.WeChatRequest;
import com.es.disped.common.wechat.http.response.AccessResponse;
import com.es.disped.common.wechat.model.TextMsg;
import com.es.disped.common.wechat.signature.WeChatSignature;
import com.es.disped.core.annotation.LogInject;
import com.es.disped.core.controller.BaseController;
import com.es.disped.dao.model.User;
import com.es.disped.dao.model.UserExample;

import io.swagger.annotations.Api;

@Api(value="微信消息推送")
@Controller
@RequestMapping("/wechat/message")
public class WeChatController extends BaseController{
	
	@LogInject
	Logger logger;
	@Autowired
	RedisTemplate<String, String> redisTemplate;
	@Autowired
	WeChatService weChatService;
	@Autowired
	UserService userService;
	

	@RequestMapping(value="/signature",method=RequestMethod.GET)
	@ResponseBody
	public String checkSignature(WeChatRequest request)
	{
		System.out.println("测试微信的接入:"+request);
        if (WeChatSignature.checkSignature(request)) {
            logger.info("校验成功，直接返回数据");
            return request.getEchostr();
        }
        logger.info("校验失败");
        return null;
	}
	
	
	
	@RequestMapping(value="/course/notice",method=RequestMethod.POST)
	public @ResponseBody MsgModel sendCourseReservationSuccessMessage(@RequestBody Map<String, Object> paramMap)
	{
		//若token在半小时内过期，则重新获取
		checkToken();
		
		
		
//		String toUser=paramMap.remove("toUser").toString();
		
		
		
        MsgModel msgModel=weChatService.sendTemplateMessage(paramMap, 
        		WeChat.TemplateMessage.COURSE_RESERVATION_SUCCESS.getValue(),
        		//toUser,
        		"oFR0dw2TCCyaXYZMa9rmF64bp3Ao",
        		redisTemplate.opsForValue().get("wechat_access_token"));
		return msgModel;
	}
	
	@RequestMapping(value="/signature",method=RequestMethod.POST)
	public void bindWeChatUser(HttpServletRequest request, HttpServletResponse response)
	{
		response.setCharacterEncoding("UTF-8");
		Map<String, String> paramMap=xmlToMap(request);
		String fromUserName=paramMap.get("FromUserName");
		String toUserName=paramMap.get("ToUserName");
		String msgType=paramMap.get("MsgType");
		String content=paramMap.get("Content");	

		
		TextMsg textMsg=new TextMsg();
		textMsg.setFromUserName(toUserName);
		textMsg.setToUserName(fromUserName);
		textMsg.setCreateTime(this.currentDate("yyyy-MM-dd HH:mm:ss"));
		if(WeChat.MessageType.TEXT.getValue().equals(msgType))
		{
			int count=0;
			if(content.length()==11)
			{
				User user=new User();
				user.setOpenId(fromUserName);
				UserExample example=new UserExample();
				example.createCriteria().andPhoneEqualTo(content);
				count=userService.updateByExampleSelective(user, example);
			}
			textMsg.setMsgType(WeChat.MessageType.TEXT.getValue());
			textMsg.setContent(count==1?"绑定成功":"绑定失败");
		}else if(WeChat.MessageType.EVENT.getValue().equals(msgType))
		{
			String eventType=paramMap.get("Event");
			if(WeChat.MessageType.EVENT_SUBSCRIBE.getValue().equals(eventType))
			{
				textMsg.setMsgType(WeChat.MessageType.TEXT.getValue());
				textMsg.setContent("感谢您的关注~\r\n请输入注册教研室平台所用的手机号进行绑定\r\n若尚未注册教研室平台，请先前往教研室平台进行注册！");
			}
		}
		try {
			response.getWriter().write(textMsgToXml(textMsg));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	
	/**
	 * 监测accessToken是否过期
	 */
	private void checkToken()
	{
		//若token在半小时内过期，则重新获取
		if(redisTemplate.getExpire("wechat_access_token", TimeUnit.SECONDS)<60*30)
		{
			MsgModel msgModel=weChatService.getAccessToken();
			if(Optional.of(msgModel)
					.filter(status->msgModel.getStatus()==HttpStatus.OK.value())
					.filter(response->msgModel.getRes()!=null)
					.filter(errcode->((AccessResponse)msgModel.getRes()).getErrorcode()==null)
					.isPresent())
			{
				AccessResponse response=(AccessResponse) msgModel.getRes();
				redisTemplate.opsForValue().set("wechat_access_token",
						response.getAccess_token(), 
						Integer.valueOf(response.getExpires_in()),
						TimeUnit.SECONDS);
			}
		}
	}
	
}
